package com.bingxue.edu.tools;

import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.management.shop.model.entity.Order;
import com.bingxue.edu.management.shop.model.entity.OrderItem;
import com.bingxue.edu.management.shop.model.entity.Refund;
import com.bingxue.edu.management.shop.service.OrderItemService;
import com.bingxue.edu.management.shop.service.OrderService;
import com.bingxue.edu.management.shop.service.RefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.math.BigDecimal;
import java.util.List;

import static com.bingxue.edu.management.shop.model.entity.table.RefundTableDef.REFUND;

/**
 * 处理重复缴费导致的订单状态异常
 * @author panbo
 * @since 2024/11/23
 */
@SpringBootTest
public class OrderRefundPriceFixedTool {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RefundService refundService;

//    @Test
//    @Transactional(rollbackFor = Exception.class)
    public void fixed() {

        List<Refund> list = refundService.queryChain().where(REFUND.REFUND_OFF.eq(true)).list();
        for (Refund refund : list) {
            Order order = orderService.getById(refund.getOrderId());
            ValidationUtils.throwIfNull(order, "order为空");
            BigDecimal refundPrice1 = order.getRefundPrice();
            if (refundPrice1 == null) {
                refundPrice1 = BigDecimal.ZERO;
            }
            refundPrice1 = refundPrice1.add(refund.getRefundPrice());
            order.setRefundPrice(refundPrice1);
            orderService.updateById(order);


            OrderItem orderItem = orderItemService.getById(refund.getOrderItemId());
            ValidationUtils.throwIfNull(orderItem, "orderItem为空");
            BigDecimal refundPrice2 = orderItem.getRefundPrice();
            if (refundPrice2 == null) {
                refundPrice2 = BigDecimal.ZERO;
            }
            refundPrice2 = refundPrice2.add(refund.getRefundPrice());
            orderItem.setRefundPrice(refundPrice2);
            orderItemService.updateById(orderItem);
        }
    }

}
